package cn.lds.j368.dsbank.service.impl;

import cn.lds.j368.dsbank.constant.DsBankConstants;
import cn.lds.j368.dsbank.domain.LoanApply;
import cn.lds.j368.dsbank.dto.RespDTO;
import cn.lds.j368.dsbank.exception.ServiceException;
import cn.lds.j368.dsbank.mapper.LoanApplyMapper;
import cn.lds.j368.dsbank.service.LoanApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
public class LoanApplyServiceImpl implements LoanApplyService {

    @Autowired
    private LoanApplyMapper loanApplyMapper;

    @Override
    public RespDTO<List<LoanApply>> selectLoanApplyAll() throws ServiceException {

        List<LoanApply> loanApplies = loanApplyMapper.selectLoanApplyAll();

        if (CollectionUtils.isEmpty(loanApplies)){
            throw new ServiceException(DsBankConstants.SysMsg.QUERY_FAIL);
        }

        return RespDTO.buildSuccess(loanApplies);
    }

    @Override
    public RespDTO<LoanApply> selectLoanApplyByApplyId(Long applyId) throws ServiceException {

        LoanApply loanApply = loanApplyMapper.selectLoanApplyByApplyId(applyId);

        if (Objects.isNull(loanApply)){
            throw new ServiceException(DsBankConstants.SysMsg.QUERY_FAIL);
        }

        return RespDTO.buildSuccess(loanApply);
    }

    @Override
    public RespDTO addOrModifyLoanApply(LoanApply loanApply) throws ServiceException {

        if (Objects.isNull(loanApply.getLoanApplyId())){
            int insert = loanApplyMapper.insert(loanApply);
            if (insert <= 0){
                throw new ServiceException(DsBankConstants.SysMsg.ADD_DATA_FAIL);
            }
        }else {
            int i = loanApplyMapper.updateById(loanApply);
            if (i < 0){
                throw new ServiceException(DsBankConstants.SysMsg.MODIFY_DATA_FAIL);
            }
        }
        return RespDTO.buildSuccess();
    }

    @Override
    public RespDTO delLoanApply(Long applyId) throws ServiceException {

        int i = loanApplyMapper.deleteById(applyId);
        if (i <= 0){
            throw new ServiceException(DsBankConstants.SysMsg.DEL_DATA_FAIL);
        }

        return RespDTO.buildSuccess();
    }
}
